package com.soft.mainsite.module.web.cms;

import cn.hutool.core.util.ArrayUtil;
import com.soft.mainsite.common.annotation.SysLog;
import com.soft.mainsite.common.constant.CmsConst;
import com.soft.mainsite.common.utils.CmsUtil;
import com.soft.mainsite.common.utils.JsonUtil;
import com.soft.mainsite.module.web.cms.service.SiteService;
import com.soft.mainsite.module.web.cms.vo.SiteQueryParams;
import com.soft.mainsite.module.web.cms.vo.TCmsSiteVo;
import com.soft.mainsite.module.web.system.service.SysUserService;
import com.soft.mainsite.module.web.system.vo.UserVo;
import com.soft.mainsite.mybatis.mapper.TCmsUserSiteMapper;
import com.soft.mainsite.mybatis.model.TCmsSite;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Description:站点控制器
 *
 * @author Jin
 * @create 2017-05-15
 **/
@Controller
@RequestMapping("/system/cms/site")
public class SiteController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private TCmsUserSiteMapper userSiteMapper;

    /**
     * 站点列表页
     *
     * @param pageNumber
     * @param pageSize
     * @param queryParams
     * @param model
     * @param request
     * @return
     */
    @RequiresPermissions("site:admin")
    @RequestMapping
    public String index(@RequestParam(value = "pageCurrent", defaultValue = "1") Integer pageNumber,
                        @RequestParam(value = "pageSize", defaultValue = "30") Integer pageSize,
                        SiteQueryParams queryParams, Model model, HttpServletRequest request) {
        UserVo userVo = ((UserVo) request.getSession().getAttribute(CmsConst.SITE_USER_SESSION_KEY));
        model.addAttribute("model", siteService.pageSiteVoListByConditions(pageNumber, pageSize, queryParams, userVo));
        model.addAttribute("pojo", queryParams);
        return "cms/site_list";
    }

    /**
     * 添加/修改站点页面
     *
     * @param id
     * @param model
     * @return
     */
    @SysLog("站点添加")
    @RequiresPermissions("site:input")
    @RequestMapping("/input")
    public String input(@RequestParam(value = "id", required = false) Integer id, Model model) {
        if (id != null) {
            TCmsSiteVo voById = siteService.findVoById(id);
            model.addAttribute("site", voById);
        }
        return "cms/site_input";
    }

    /**
     * 添加/修改站点
     *
     * @param pojo
     * @return
     */
    @RequiresPermissions("site:save")
    @RequestMapping("/save")
    @ResponseBody
    public String save(TCmsSiteVo pojo) {
        if (pojo.getSiteId() != null) {
            return siteService.update(pojo);
        }
        return siteService.save(pojo);
    }

    /**
     * 站点批量添加
     *
     * @return
     */
    @SysLog("站点批量添加")
    @RequestMapping("/inputMore")
    public String inputMore() {
        return "cms/site_input_more";
    }

    /**
     * 批量添加子站点
     *
     * @param siteNum
     * @return
     */
    @RequestMapping("/saveMore")
    @ResponseBody
    public String saveMore(@RequestParam(value = "siteNum", required = false) Integer siteNum) {
        return siteService.saveMore(siteNum);
    }

    /**
     * 初始化站点（根据城市创建所有站点）
     *
     * @param siteNum
     * @return
     */
    @RequestMapping("/initInputMore")
    @ResponseBody
    public String initInputMore(@RequestParam(value = "siteNum", required = false) Integer siteNum) {
        return siteService.initInputMore();
    }

    /**
     * 删除站点
     *
     * @param ids
     * @return
     */
    @RequiresPermissions("site:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(@RequestParam(value = "ids", required = false) Integer[] ids) {
        return siteService.delete(ids);
    }

    /**
     * 批量删除子站点（没有选择城市子站点）
     *
     * @return
     */
    @RequestMapping("/deleteMore")
    @ResponseBody
    public String deleteMore() {
        return siteService.deleteMore();
    }

    /**
     * 切换站点
     *
     * @param id
     * @param request
     * @return
     */
    @RequiresPermissions("site:change")
    @RequestMapping("/change")
    @ResponseBody
    public String change(@RequestParam(value = "id", required = false) Integer id, HttpServletRequest request) {
        UserVo userVo = ((UserVo) request.getSession().getAttribute(CmsConst.SITE_USER_SESSION_KEY));
        return siteService.change(userVo, id);
    }

    /**
     * 选择管理员
     *
     * @param pageNumber
     * @param pageSize
     * @param siteId
     * @param user
     * @param request
     * @return
     */
    @RequestMapping("/userCheck")
    public ModelAndView userCheck(
            @RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
            @RequestParam(value = "pageSize", defaultValue = "30") Integer pageSize,
            @RequestParam("siteId") Integer siteId, UserVo user, HttpServletRequest request) {
        ModelAndView view = new ModelAndView("cms/user_check");
        UserVo userVo = ((UserVo) request.getSession().getAttribute(CmsConst.SITE_USER_SESSION_KEY));
        user.setUserId(userVo.getUserId());
        view.addObject("model", userService.findSiteUserPageInfo(pageNumber, pageSize, user));
        view.addObject("modelSelect", userSiteMapper.selectBySiteId(siteId));
        view.addObject("user", user);
        view.addObject("siteId", siteId);
        return view;

    }

    /**
     * 校验域名
     *
     * @param domain
     * @return
     */
    @RequestMapping("/checkDomain")
    @ResponseBody
    public String checkDomain(@RequestParam(value = "domain", required = false) String domain) {
        if (!CmsUtil.isNullOrEmpty(siteService.findByDomain(domain))) {
            return "{\"error\": \"域名已存在\"}";
        }
        return "{\"ok\": \"验证通过\"}";
    }

    /**
     * 校验管理是否存在
     *
     * @param userId
     * @return
     */
    @RequestMapping("/checkAdmin")
    @ResponseBody
    public String checkAdmin(@RequestParam(value = "userId", required = false) Integer userId) {
        if (CmsUtil.isNullOrEmpty(userService.findSysUserByUserId(userId))) {
            return "{\"error\": \"管理不存在！\"}";
        }
        return "{\"ok\": \"验证通过\"}";
    }

    /**
     * 校验城市是否重复（现在不用）
     *
     * @param cityCode
     * @param siteId
     * @return
     */
    @RequestMapping("/checkCity")
    @ResponseBody
    public String checkCity(@RequestParam(value = "cityCode", required = false) Integer cityCode, @RequestParam(value = "siteId", required = false) Integer siteId) {
        if (!CmsUtil.isNullOrEmpty(siteService.findByCityCode(cityCode, siteId))) {
            return "{\"error\": \"城市已存在站点\"}";
        }
        return "{\"ok\": \"验证通过\"}";
    }


    @RequestMapping("/findSite")
    @ResponseBody
    public String findSite(@RequestBody String[] siteIds) {
        if (ArrayUtil.isEmpty(siteIds)) {
            return JsonUtil.toError("请至少选择一个站点");
        }
        Map<String, Object> siteStaticError = siteService.findSiteStatic(siteIds);
        return JsonUtil.objectTojson(siteStaticError);
    }

    @RequestMapping("/findAllSiteStatus")
    @ResponseBody
    public String findAllSiteStatus() {
        List<TCmsSite> siteStaticError = siteService.findAllSiteStaticByStatus(CmsConst.SITE_STATIC_ERROR);
        return JsonUtil.objectTojson(siteStaticError);
    }

}
